package log_aop;

import com.yangjicong.o2o.studey.base.common.exception.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.slf4j.helpers.BestpayMarker;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.yangjicong.o2o.studey.base.common.exception.ExceptionUtils;
import utils.BaseUtil;


@Component
@Aspect
@Slf4j
@Order
public class LogAop {


    @Pointcut("@within(log_aop.OperationLog) || @annotation(log_aop.OperationLog)")
    public void logAdvicePointcut() {
        //日志切点
    }


    @Around("logAdvicePointcut()")
    public Object logAroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("我是aop,我进来了");
        long startTime = System.currentTimeMillis();
        //获取类名称
        String className = joinPoint.getTarget().getClass().getSimpleName();
        //获取方法名称
        String methodName = joinPoint.getSignature().getName();
        //获取参数
        Object[] params = joinPoint.getArgs();
        Result result;
        try {
            //参数校验
            if (ArrayUtils.isNotEmpty(params)) {
                // ParamValidate.validateParams(params[0]);
            }
            MDC.put(BestpayMarker.TRACE_LOG_ID, BaseUtil.queryTraceLogId(params[0]));
            log.info("call [{}] [{}] PARAMETER:[{}]", className, methodName, ArrayUtils.toString(params));
            result = (Result) joinPoint.proceed();
            log.info("call[{}] [{}] [{}ms] [Success] [{}] RESPONSE:Result[{}]", className, methodName, System.currentTimeMillis() - startTime, result.isSuccess(), result);
        } catch (Throwable err) {
            result = ExceptionUtils.doExceptionService(err);
            log.error("call[{}] [{}] [{}ms] [Failure] [{}] RESPONSE:Result[{}] EXCEPTION:[{}]", className, methodName, System.currentTimeMillis() - startTime, result.isSuccess(), result, err);
        } finally {
            MDC.clear();
        }
        return result;
    }
}
